package com.example.springsecurity.authentication;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: anwenbiao
 * @Description: TODO 自定义短息密码过滤器
 * @DateTime: 2023/2/4 22:28
 */
public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String MOBILE_PHONE = "mobilePhone";
    private String CODE = "code";

    private boolean postOnly = true;

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/smsLogin", "POST");

    public SmsAuthenticationFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    public SmsAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
    }
    
    

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String mobilePhone = request.getParameter(MOBILE_PHONE);
            mobilePhone = mobilePhone != null ? mobilePhone.trim() : "";
            String code = request.getParameter(CODE);
            code = code != null ? code : "";
//            构建token
            SmsAuthenticationToken smsAuthenticationToken = SmsAuthenticationToken.unauthenticated(mobilePhone, code);
            this.setDetails(request, smsAuthenticationToken);
//            认证
            return this.getAuthenticationManager().authenticate(smsAuthenticationToken);
        }
       
    }

    protected void setDetails(HttpServletRequest request, SmsAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    
}
